'use strict';
	angular.module('autoentry.draftVoucherSingle', [])

	.controller('draftVoucherSingleCtrl'
			,['$rootScope', '$scope','systemService'  ,'BizData', 'apiService'
			   , f])//控制器结束
	function f($rootScope,$scope, systemService , BizData, apiService) {
		var common = require('common');
		
		var Model = this;
//		$scope.path = $rootScope.path;
//		$scope.createPermission = $rootScope.path + ':create';
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码

		var flowType = 0;
		var billType = 'YBPZ';
		var billTypeName = "一般凭证";

		var origin="1";
		var originName = "1.一般凭证输入";

		var autoCode; //是否自动编码

		/////////////////////////////////////////////////////////////////////////////////////////////////

		var direction = 1;
//		var departmentNo;
//		var departmentName;
		var employeeNo;
		var employeeName;

		var voucherNo;
		var maxDetailNo;
		var serialNo;
		
		var billNo;

		var state;
		var status;
		var audit;
		var orderDate;
		
		var userId;
		var enterpriseNo;
		var enterpriseName;
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
		
		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){
			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			event.source.setValue('billType',billType,event.id);
			event.source.setValue('billTypeName',billTypeName,event.id);
			
			event.source.setValue('direction',direction,event.id);
		}

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}

		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {
			if(event.rowID!=null){
				Model.dataDetail.fMasterID = event.rowID;
	       		Model.dataDetail.refreshData();
			}else{
				Model.dataDetail.clearData();
			}
		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			if(event.column=='direction'){
				var rowID = event.source.getID(event.rowIndex);
				var direction = event.source.getValue('direction',rowID);
//				var dataDetail = Model.dataDetail;
				//从表
				var slaveDatas = event.source.slaveDatas;
				var dataDetail = event.source.container[slaveDatas[0]];
				for(var i=0;i<dataDetail.getCount();i++){
					dataDetail.setValue('direction',direction,dataDetail.getID(i));
				}
			}
			if(event.column=='orderDate'){
				var rowID = event.source.getID(event.rowIndex);
				var orderDate = event.source.getValue('orderDate',rowID);
//				var dataDetail = Model.dataDetail;
				//从表
				var slaveDatas = event.source.slaveDatas;
				var dataDetail = event.source.container[slaveDatas[0]];
				for(var i=0;i<dataDetail.getCount();i++){
					dataDetail.setValue('orderDate',orderDate,dataDetail.getID(i));
				}
			}
			if(event.column=='employeeNo'){
				var rowID = event.source.getID(event.rowIndex);
				var employeeNo = event.source.getValue('employeeNo',rowID);
				var employeeName = event.source.getValue('employeeName',rowID);
//				var dataDetail = Model.dataDetail;
				//从表
				var slaveDatas = event.source.slaveDatas;
				var dataDetail = event.source.container[slaveDatas[0]];
				for(var i=0;i<dataDetail.getCount();i++){
					dataDetail.setValue('employeeNo',employeeNo,dataDetail.getID(i));
					dataDetail.setValue('employeeName',employeeName,dataDetail.getID(i));
				}
			}
			/*
			if (event.column == "periodNo" || event.column == "orderDate") {
				var dataMaster = event.source;
				var rowID =  dataMaster.getID(event.rowIndex);
				var periodStatus = dataMaster.getValue("periodStatus", rowID);
				var periodNo = dataMaster.getValue("periodNo", rowID);
				var orderDate = dataMaster.getValue("orderDate", rowID);
				if(periodStatus=="Y" && periodNo!=null && periodNo!="" && orderDate!=null && orderDate!=""){
					if(periodValid(periodNo,orderDate)==false){
						dataMaster.setValue("orderDate",null,rowID);
					}
				}
			}
			*/
			if(event.column == 'debitAmount' || event.column == 'creditAmount'){
				
				var rowID = event.source.getID(event.rowIndex);
				var debitAmount = event.source.getValue('debitAmount',rowID);
				var creditAmount = event.source.getValue('creditAmount',rowID);
				
				//计算大写金额
				var wordsAmount = '';
				if(debitAmount == creditAmount){
					wordsAmount = common.num2ChMoney(debitAmount);
				}else{
					wordsAmount = '';
				}
				
				event.source.setValue('wordsAmount',wordsAmount,rowID);
				
			}
		};
		
		
		Model.dataMasterBeforeSave = function(event) {
			var rowID = event.source.getCurrentID();
			var debitAmount = event.source.getValue('debitAmount',rowID);
			var creditAmount = event.source.getValue('creditAmount',rowID);
			if(debitAmount!=creditAmount){
				event.cancel = true;
				alert('借方金额与贷方金额不相等，无法保存！');
			}
		};
		
		
		Model.dataMasterAfterSave = function(event) {
			//保存子表
//			Model.dataDetail.saveData();
			
		}
		

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataDetailBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
//			event.cancel = true;
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataDetailAfterDelete = function(event) {
			//获取主data
			var dataMaster = event.source.masterData;
//			console.log('主data-->',dataMaster);
			if(dataMaster!=null){
				var masterRowID = dataMaster.getCurrentID();
				//更新主表中子表记录数
				dataMaster.setValue('detailsCount', dataMaster.getValue('detailsCount', masterRowID) - 1, masterRowID);	
				
				//计算主表合计
				//数量
				var column="debitAmount";
				var sum = event.source.getSum(column);
				dataMaster.setValue(column,sum,masterRowID);
				//金额
				column="creditAmount";
				sum = event.source.getSum(column);
				dataMaster.setValue(column,sum,masterRowID);
			}
		}
		
		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataDetailIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataDetailDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataDetailValueChanged = function(event) {
			if(event.column == 'debitAmount' || event.column == 'creditAmount'){
				
				//改变主表汇总值
				//获取主data
				var dataMaster = event.source.masterData;
//				console.log('主data-->',dataMaster);
				//更新主表的汇总值
				var sum = event.source.getSum(event.column);
				if (isNaN(sum)){sum = 0;} 
				dataMaster.setValue(event.column,sum,dataMaster.getCurrentID());

			}

			if(event.column=='dob' || event.column=='entryAmount'){
				var rowID = event.source.getID(event.rowIndex);
				var dob = event.source.getValue('dob',rowID);
				var entryAmount = event.source.getValue('entryAmount',rowID);
				if(dob==1){
					event.source.setValue('debitAmount', entryAmount, rowID);
					event.source.setValue('creditAmount', 0, rowID);
				}
				if(dob==-1){
					event.source.setValue('debitAmount', 0, rowID);
					event.source.setValue('creditAmount', entryAmount, rowID);
				}
			}

		}
		

		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataDetailBeforeNew = function(event) {
			// 明细数据新增之前
			// 检查主表中的数据是否完整
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			
			state = dataMaster.getValue('state', rowID);
			status = dataMaster.getValue('status', rowID);
			audit = dataMaster.getValue('audit', rowID);
			orderDate = dataMaster.getValue('orderDate', rowID);
			
			//////////////////////////////////////////////////////////////////////
			systemCode = dataMaster.getValue('systemCode', rowID);
			//////////////////////////////////////////////////////////////////////


			billType = dataMaster.getValue('billType', rowID);
			direction = dataMaster.getValue('direction', rowID);
//			departmentNo = dataMaster.getValue('departmentNo', rowID);
//			departmentName = dataMaster.getValue('departmentName', rowID);
			employeeNo = dataMaster.getValue('employeeNo', rowID);
			employeeName = dataMaster.getValue('employeeName', rowID);

			voucherNo = dataMaster.getValue('voucherNo', rowID);
			
			//处理从表流水号
			maxDetailNo=dataMaster.getValue('maxDetailNo', rowID);
			maxDetailNo++;
			var detailNo=common.preZeroFill(maxDetailNo, 5);
			serialNo=detailNo;
				
			billTypeName = dataMaster.getValue('billTypeName', rowID);
			
			userId = dataMaster.getValue('userId', rowID);
			enterpriseNo = dataMaster.getValue('enterpriseNo', rowID);
			enterpriseName = dataMaster.getValue('enterpriseName', rowID);

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataDetailAfterNew = function(event){
			var dataDetail = event.source;
			var rowID = event.id;

			dataDetail.setValue('state', state, rowID);
			dataDetail.setValue('status', status, rowID);
			dataDetail.setValue('audit', audit, rowID);
			dataDetail.setValue('orderDate', orderDate, rowID);

			dataDetail.setValue('billType', billType, rowID);
			dataDetail.setValue('direction', direction, rowID);
//			dataDetail.setValue('departmentNo', departmentNo, rowID);
//			dataDetail.setValue('departmentName', departmentName, rowID);
			dataDetail.setValue('employeeNo', employeeNo, rowID);
			dataDetail.setValue('employeeName', employeeName, rowID);

			dataDetail.setValue('voucherNo', voucherNo, rowID);	

			dataDetail.setValue('serialNo', serialNo, rowID);

			////////////////////////////////////////////////////////////////////////////////////
			dataDetail.setValue('systemCode', systemCode, rowID);
			/////////////////////////////////////////////////////////////////////////////////////////
			
			dataDetail.setValue('billTypeName', billTypeName, rowID);
			
			//更新主表计数器（从表最大流水号）
			var dataMaster = Model.dataMaster;
			var masterRowID = dataMaster.getCurrentID();
			dataMaster.setValue('maxDetailNo', maxDetailNo, masterRowID);	
			
			//更新主表中子表记录数
			dataMaster.setValue('detailsCount', dataMaster.getValue('detailsCount', masterRowID) + 1, masterRowID);	

			dataDetail.setValue('userId', userId, rowID);
			dataDetail.setValue('enterpriseNo', enterpriseNo, rowID);
			dataDetail.setValue('enterpriseName', enterpriseName, rowID);

			dataDetail.setValue('fMasterID',dataDetail.fMasterID,rowID);

		}
		
		///////////////////按钮组开始///////////////////////////////////////////////////
		//新建
		Model.add = function(){
			
		     var options = {
			         index : 0,
			         defaultValues : [
			             {
			            	 state:'active'
			            	 ,status:'open'
			            	 ,audit:'active'
			            	 
			            	 ,debitAmount:0
			            	 ,creditAmount:0
			            	 ,attachQuantity:0
			            	 
			            	 ,formalFlag: 0 
			            	 ,draftFlag: 1
			            	
			            	 ,detailsCount:0
			            	 ,maxDetailNo:0
			            	 
			            	 ,billType: billType
			            	 ,orderDate: ':getCurrentDate()'
				             ,employeeNo: ':getCurrentPsmFID()'
					         ,employeeName: ':getCurrentPsmFName()'
				             ,cUsercode: ':getCurrentPersonCode()'
					         ,cUsername: ':getCurrentPersonName()'
						     ,cDatetime: ':getCurrentDateTime()'
							 ,userId: ':getCurrentPersonID()'
							 ,enterpriseNo: ':getCurrentOgnFID()'
							 ,enterpriseName: ':getCurrentOgnLongName()'
							 ,version: 0

			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataMaster.newData(options);

			if($scope.tabpanel!='single'){
				$scope.tabpanel='single'
			}
		}
		//修改
		Model.edit = function(){
			Model.dataMaster.editData();
			if($scope.tabpanel!='single'){
				$scope.tabpanel='single'
			}
		}
		
		//保存
		Model.save = function() {
			Model.dataMaster.saveData();
		}

		//取消编辑
		Model.saveCancel = function() {
			Model.dataMaster.editCancel();
		}
		
		/*
		//不提示直接提交后台删除当前行
		var data = justp.xbl('mainData');
		var deleteConfirm = data.deleteConfirm;
		var directDeleteMode = data.directDeleteMode;
		try{
		    data.deleteConfirm = false;
		    data.directDeleteMode = true;
		    data.deleteData(data.getID());
		}finally{
		    data.deleteConfirm = deleteConfirm;
		    data.directDeleteMode = directDeleteMode;
		}
		*/
		Model.remove = function() {
			Model.dataMaster.deleteData(Model.dataMaster.getCurrentID());
			Model.dataMaster.refreshData();
		};
		
		//刷新
		Model.refresh = function() {
			Model.dataMaster.refreshData();
		}
		
		
		//输出：在浏览器窗口打开/下载打印（打印和导出）
		Model.printExport = function() {
			var options = {};
			options.path = $rootScope.getServiceName() + $rootScope.path + "/printPDF";
			options.id = Model.dataMaster.getCurrentID();
			if($rootScope.separation==0){
				//整体项目
				systemService.openPrintExportWindow(options); 
			}else{
				//前后端分离
				systemService.downloadExport(options); 
			}
		};

		///////////////////按钮组结束///////////////////////////////////////////////////
		///////////////////子表按钮组开始///////////////////////////////////////////////////
		//增加
		Model.addrow = function(){
		     var options = {
			         index : Model.dataDetail.getCount(),
			         defaultValues : [
			             {
			            	 debitAmount:0
			            	 ,creditAmount:0
			            	 ,balanceAmount:0
			            	 ,entryAmount:0
			            	 ,dob:1
			            }//,
//			             {itemNo:'a2',itemDescribe:'b2'}
			         ]
			     };    

			Model.dataDetail.newData(options);
		};
		
		Model.delrow = function() {
			 if(Model.dataDetail.directDeleteMode){
				//直接删除
				 if(Model.dataDetail.deleteData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.refreshData();
				 }
			 }else{
				//前台移除
				 if(Model.dataDetail.removeData(Model.dataDetail.getCurrentID())==0){
//					 Model.dataDetail.recordState = 'delete';
				 }
			 }
		};
		///////////////////子表按钮组结束///////////////////////////////////////////////////

		
		
		//打开对话框（选择客户）
		Model.triggerProviderNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var customerNo = dataMaster.getValue('customerNo', rowID);
     		if(customerNo!=null && customerNo!=''){
//         		dataMaster.setValue('dealObject', null, rowID);
//         		dataMaster.setValue('dealObjectLabel', null, rowID);
         		dataMaster.setValue('customerID', null, rowID);
         		dataMaster.setValue('customerNo', null, rowID);
         		dataMaster.setValue('shortName', null, rowID);
         		dataMaster.setValue('customerName', null, rowID);
     			return;
     		}

			var options = {};
			
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openCustomerNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
//	             		dataMaster.setValue('dealObject', returnData[i].storageTypeD, rowID);
//	             		dataMaster.setValue('dealObjectLabel', returnData[i].storageTypeDLabel, rowID);
	             		dataMaster.setValue('customerID', returnData[i].fID, rowID);
	             		dataMaster.setValue('customerNo', returnData[i].customerNo, rowID);
	             		dataMaster.setValue('shortName', returnData[i].shortName, rowID);
	             		dataMaster.setValue('customerName', returnData[i].customerName, rowID);
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
		}
		
		

		//打开对话框（选择经办人）
		Model.triggerEmployeeNoClick = function(){
			
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var employeeNo = dataMaster.getValue('employeeNo', rowID);
     		if(employeeNo!=null && employeeNo!=''){
         		dataMaster.setValue('employeeNo', null, rowID);
         		dataMaster.setValue('employeeName', null, rowID);
     			return;
     		}
			
			
			var options = {};
			options.id = dataMaster.getValue('enterpriseNo',rowID);
			//是否显示人员
			options.psm = true;

			var modalInstance = apiService.openOrgNoDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	             	for ( var i = 0; i < returnData.length; i++) {
//	             		alert(returnData[i].sID+'-->'+returnData[i].sFName);
	             		dataMaster.setValue('employeeNo', returnData[i].sFID, rowID);
	             		dataMaster.setValue('employeeName', returnData[i].sFName, rowID);
	         			
	                 }
	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//打开对话框（选择会计科目）
		Model.grid_captionNoClick = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var options = {};
			options.recordState = 'none';
			options.id = dataMaster.getValue('enterpriseNo',rowID);

			var modalInstance = systemService.openCaptionNoDialog(options);

	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
				
	     		var dataDetail = Model.dataDetail;
	     		var rowID = dataDetail.getCurrentID();

         		dataDetail.setValue('captionID', returnData[0].fID, rowID);
         		dataDetail.setValue('captionNo', returnData[0].captionNo, rowID);
         		dataDetail.setValue('captionName', returnData[0].captionName, rowID);
         		dataDetail.setValue('captionFullName', returnData[0].captionFullName, rowID);

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};
		
		//过账后者撤回
	    Model.posting = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
			var voucherNo = dataMaster.getValue('voucherNo',rowID);
			var enterpriseNo = dataMaster.getValue('enterpriseNo',rowID);

	    	var options = {};
	    	options.voucherNo = voucherNo;
	    	options.enterpriseNo = enterpriseNo;
	    	
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/autoentry/draftVoucher/single/posting",
	            data: JSON.stringify(options),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
					console.log('data->',data);
					if(data.code==0){
						Model.dataMaster.refreshPageData();
						$scope.$apply();
					}else{
						alert(data.info);
					}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };

		
		
		/////////////////////////////////////////////////////////////////////
		Model.triggerConfirmClick = function(event){
			//提交之前
			var options = new Object();
			options.bizData = Model.dataMaster;
			if(systemService.ysyfConfirmBefore(options)==false){
				return;
			}
			// 提交单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/autoentry/draftVoucher/single/confirm';
			systemService.operateBill(data);
		};
		
		Model.triggerActiveClick = function(event){
			// 撤销提交
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/autoentry/draftVoucher/single/active';
			systemService.operateBill(data);
		};
		
		Model.triggerAgreeItClick = function(event){
			var dataMaster = Model.dataMaster;
			var rowID = Model.dataMaster.getCurrentID();
			// 审核单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/autoentry/draftVoucher/single/agreeIt';
			var response = systemService.operateBill(data);
		
		};
		
		Model.triggerUnAgreeClick = function(event){
			// 撤销审核
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/autoentry/draftVoucher/single/unAgree';
			systemService.operateBill(data);
		};
		
		Model.triggerCloseClick = function(event){
			// 关闭单据
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/autoentry/draftVoucher/single/close';
			systemService.operateBill(data);
		};
		
		Model.triggerOpenClick = function(event){
			// 撤销审核
			var data = new Object();
			data.bizData = Model.dataMaster;
			data.url = $rootScope.getServiceName() + '/autoentry/draftVoucher/single/open';
			systemService.operateBill(data);
		};

		///////////////////////////////////////////////////////////////////////////////
		
		
		//双击事件
		Model.gridListRowDblclick = function(rowIndex,rowID){
			$scope.tabpanel = 'single';
		}
		

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//		Model.objects = {"dataMaster" : Model.dataMaster,"dataDetail" : Model.dataDetail};
		
		var options = {};
		options.container = Model;
		options.concept = 'AccountVoucher';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/autoentry/draftVoucher/single/create';
		options.reader = '/autoentry/draftVoucher/single/query';
		options.writer = '/autoentry/draftVoucher/single/save';
		options.deleter = '/autoentry/draftVoucher/single/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"","relation":""};
		options.directDeleteMode = true;
		options.limit = 15;
		options.orderBy = "cDatetime DESC";

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);
//		Model.objects.dataMaster = Model.dataMaster;
		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值

		
		
		var options = {};
		options.container = Model;
		options.concept = 'AccountVoucherDetail';
		options.name = 'dataDetail';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.reader = '/autoentry/draftVoucher/single/queryDetail';
		options.creater = '/autoentry/draftVoucher/single/createDetail';
		options.deleter = '';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"dataMaster","relation":"fMasterID"};
		options.directDeleteMode = false;
		options.orderBy = 'serialNo ASC';
		

		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataDetailIndexChanged;
		options.onBeforeNew = Model.dataDetailBeforeNew;
		options.onAfterNew = Model.dataDetailAfterNew;
		options.onBeforeDelete = Model.dataDetailBeforeDelete;
		options.onAfterDelete = Model.dataDetailAfterDelete;
		options.onValueChanged = Model.dataDetailValueChanged;
		options.onDataChanged = Model.dataDetailDataChanged;
//		options.rowsWatcherFn = Model.rowsWatcherFn;
		
		Model.dataDetail = new BizData(options);
//		Model.objects.dataDetail = Model.dataDetail;
		//监视对象中的所有变动
		Model.dataDetail.deregRows = $scope.$watch('Model.dataDetail.rows',Model.dataDetail.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		Model.dataMaster.filter = "AccountVoucher.draftFlag=1";

		
		//生成会计凭证//////////////////////////////////////////////////////////////////
		Model.formalKJPZ = function(){
			var dataMaster = Model.dataMaster;
			var rowID = dataMaster.getCurrentID();
   		
    		if(rowID==null || rowID==undefined || rowID==''){
    			alert('单号不能为空！');
    			return;
    		}
    		
    		var msg = "确定要生成会计凭证吗？";
    		var formalFlag = dataMaster.getValue('formalFlag', rowID);
    		if(formalFlag==0){
    			msg = "确定要生成会计凭证吗？";
    		}else{
    			msg = "确定要撤销会计凭证吗？";
    		}
    		
			if (confirm(msg)==false){
				return
			}
    		
    		var options={
            	"rowID" : rowID
            };
    		
			
			$.ajax({
	            type: "POST",
	            async : true,
	            url: $rootScope.getProjectName() + "/autoentry/draftVoucher/single/formalKJPZ",
	            data: JSON.stringify(options),//{billType:data.billType,ognID:data.ognID},
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
	            	console.log('data->',data);
	            	if(data.code==0){
		    			Model.dataMaster.refreshPageData();
	        			$scope.$apply();
	            	}else{
		            	alert(data.info);
	            	}
	            }
	        });
			
		};
		
		/////////////////////////////////////////////////////////////////////////////////////
		
		
		$scope.tabpanel = 'list';

		var winParams = $rootScope.winParams;
//		console.log('窗口打开时的参数1',winParams);
		if(winParams!=undefined && winParams!=null && winParams!=''){
			if(winParams.fID){
				Model.dataMaster.id = winParams.fID;
				$scope.tabpanel = 'single';
				Model.dataMaster.refreshData();
			}
			//隐藏/显示编辑工具条
//			if(winParams.type){
//				$scope.type = winParams.type;
//			}
			if(winParams.billNo){
				//增加过滤器，只显示本人及本公司的数据
				Model.dataMaster.filter = "AccountVoucher.draftFlag=1" 
					//+ " AND AccountVoucher.billType='" + billType + "'"
					+ " AND AccountVoucher.voucherNo='" + winParams.billNo + "'"
					;
				$scope.tabpanel = 'single';
				Model.dataMaster.refreshData();
			}
			
		}else{
			
			//增加过滤器，只显示本人及本公司的数据
			Model.dataMaster.filter = "AccountVoucher.draftFlag=1" 
				//+ " AND AccountVoucher.billType='" + billType + "'"
				;
			
			Model.dataMaster.refreshData();
			
		}

		
	    return Model;
	}	
	
